const fetch = require('node-fetch-commonjs').default;
var express = require('express');
var router = express.Router();
var fs = require('fs')

let slug_list = []

// 读取用户列表
fs.readFile('./users.txt', 'utf8', (err, data) => {
    if (err) {
        console.error(err)
        process.exit(-1)
    }
    slug_list = data.split('\n').filter((x) => x.length != 0)
    console.log(slug_list)
})

async function get_submission(slug) {
    return await fetch("https://leetcode-cn.com/graphql/", {
      "headers": {
        "accept": "*/*",
        "accept-language": "en-US",
        "content-type": "application/json",
        "sec-ch-ua": "\"Chromium\";v=\"94\", \"Google Chrome\";v=\"94\", \";Not A Brand\";v=\"99\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Linux\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "x-definition-name": "recentSubmissions",
        "x-operation-name": "recentSubmissions",
        "x-timezone": "Asia/Shanghai",
      },
      "referrer": "https://leetcode-cn.com/u/" + slug + "/",
      "referrerPolicy": "strict-origin-when-cross-origin",
      "body": "{\"operationName\":\"recentSubmissions\",\"variables\":{\"userSlug\":\"" + slug + "\"},\"query\":\"query recentSubmissions($userSlug: String!) {\\n  recentSubmissions(userSlug: $userSlug) {\\n    status\\n    lang\\n    source {\\n      sourceType\\n      ... on SubmissionSrcLeetbookNode {\\n        slug\\n        title\\n        pageId\\n        __typename\\n      }\\n      __typename\\n    }\\n    question {\\n      questionFrontendId\\n      title\\n      translatedTitle\\n      titleSlug\\n      __typename\\n    }\\n    submitTime\\n    __typename\\n  }\\n}\\n\"}",
      "method": "POST",
      "mode": "cors"
    }).then((r) => r.json());
}

async function get_user_profile(slug) {
    return await fetch("https://leetcode-cn.com/graphql/", {
      "headers": {
        "accept": "*/*",
        "accept-language": "en-US",
        "content-type": "application/json",
        "sec-ch-ua": "\"Chromium\";v=\"94\", \"Google Chrome\";v=\"94\", \";Not A Brand\";v=\"99\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Linux\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "x-definition-name": "userProfilePublicProfile",
        "x-operation-name": "userPublicProfile",
        "x-timezone": "Asia/Shanghai",
      },
      "referrer": "https://leetcode-cn.com/u/" + slug + "/",
      "referrerPolicy": "strict-origin-when-cross-origin",
      "body": "{\"operationName\":\"userPublicProfile\",\"variables\":{\"userSlug\":\"" + slug + "\"},\"query\":\"query userPublicProfile($userSlug: String!) {\\n  userProfilePublicProfile(userSlug: $userSlug) {\\n    username\\n    haveFollowed\\n    siteRanking\\n    profile {\\n      userSlug\\n      realName\\n      aboutMe\\n      userAvatar\\n      location\\n      gender\\n      websites\\n      skillTags\\n      contestCount\\n      asciiCode\\n      medals {\\n        name\\n        year\\n        month\\n        category\\n        __typename\\n      }\\n      ranking {\\n        rating\\n        ranking\\n        currentLocalRanking\\n        currentGlobalRanking\\n        currentRating\\n        ratingProgress\\n        totalLocalUsers\\n        totalGlobalUsers\\n        __typename\\n      }\\n      skillSet {\\n        langLevels {\\n          langName\\n          langVerboseName\\n          level\\n          __typename\\n        }\\n        topics {\\n          slug\\n          name\\n          translatedName\\n          __typename\\n        }\\n        topicAreaScores {\\n          score\\n          topicArea {\\n            name\\n            slug\\n            __typename\\n          }\\n          __typename\\n        }\\n        __typename\\n      }\\n      socialAccounts {\\n        provider\\n        profileUrl\\n        __typename\\n      }\\n      __typename\\n    }\\n    educationRecordList {\\n      unverifiedOrganizationName\\n      __typename\\n    }\\n    occupationRecordList {\\n      unverifiedOrganizationName\\n      jobTitle\\n      __typename\\n    }\\n    submissionProgress {\\n      totalSubmissions\\n      waSubmissions\\n      acSubmissions\\n      reSubmissions\\n      otherSubmissions\\n      acTotal\\n      questionTotal\\n      __typename\\n    }\\n    __typename\\n  }\\n}\\n\"}",
      "method": "POST",
      "mode": "cors"
    }).then((f) => f.json());
    //.then((j) => console.log(j.data.userProfilePublicProfile.profile.userAvatar))
}

function get_problem_info(problem) {
    return {
        'solved': problem['status'] == 'A_10',
        'name': problem['question']['translatedTitle'],
        'submitTime': problem['submitTime'],
        'slug': problem.question.titleSlug,
        'frontendId': problem.question.questionFrontendId,
    }
}

function filter_today(info_list) {
    // 去掉重复题目
    let problem_set = new Set();
    let success_set = new Set();

    let now = new Date();
    let filtered = [];
    info_list.forEach((info) => {
        let submitTime = new Date(info.submitTime * 1000);

        if (submitTime.getDate() == now.getDate() && submitTime.getMonth() == now.getMonth() 
            && submitTime.getYear() == now.getYear() && !problem_set.has(info.slug)) {
            filtered.push(info);
            problem_set.add(info.slug);
            if (info.solved) {
                success_set.add(info.slug);
            }
        }
    })
    for (let i in filtered) {
        problem = filtered[i];
        problem.solved = success_set.has(problem.slug);
    }
    return filtered;
}

async function get_user_status(slug) {
    let data = {
        'user_slug': slug,
        'problem_count': 0,
        'problems': [],
    }

    let questions = [];
    let submissions = await get_submission(slug);
    let info = filter_today(submissions.data.recentSubmissions.map((x) => get_problem_info(x)));
    data.problems = info;

    return data;
}

async function get_all_user_status() {
    let res = [];
    for (let i in slug_list) {
        let slug = slug_list[i];
        let s = await get_user_status(slug);
        res.push(s);
    }

    // 按照做题数量排序
    res.sort((a,b) => b.problems.length - a.problems.length);
    return res;
}

/* GET home page. */
router.get('/', async function(req, res, next) {
  let user_status_list = await get_all_user_status();
  res.render('index', { title: 'Express' , status_list: user_status_list});
});

module.exports = router;
